<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 20px 0">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/roles' }">角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col>
        <el-button type="primary" style="margin-bottom: 10px" @click="addRoles">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 角色分配 -->
    <el-card>
      <el-table :data="rolesList" border stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bb', index1 == 0 ? 'bt' : '', 'aic']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="6">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限 -->
              <el-col :span="18">
                <!-- 渲染二级权限 -->
                <el-row :class="['bt', index2 == 0 ? '' : 'bt', 'aic']" v-for="(item2, index2) in item1.children" :key="item2.id">
                  <el-col :span="5" style="display: ">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="13">
                    <el-tag type="warning" closable v-for="item3 in item2.children" :key="item3.id" @close="removeRightByTagId(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modify(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row)"></el-button>
            <el-tooltip class="item" effect="light" content="分配权限" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="rightsShow(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightVisible" width="50%" @close="rightsNone">
      <el-tree :data="rightsList" :props="defaultProps" :default-checked-keys="checkedKeys" node-key="id" show-checkbox default-expand-all ref="rightsTree"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addVisible" width="50%" @close="addNode">
      <el-form :model="addRoleForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth">
          <el-input v-model="addRoleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="defineaddRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改内容 -->
    <el-dialog title="修改内容" :visible.sync="modifyVisible">
      <el-form :model="modifyForm">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="modifyForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="modifyForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleDefine">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 存放角色列表
      rolesList: [],
      // 权限数据
      rightsList: [],
      // 控制权限对话框的显示隐藏
      rightVisible: false,
      // 树形菜单渲染设置
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      // 树形菜单默认选中的选择
      checkedKeys: [],
      // 当前角色的id
      roleId: '',
      // 控制添加角色的显示或隐藏
      addVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      formLabelWidth: '100px',
      // 存放添加后的数据
      addRolesList: [],
      // 修改内容
      // 编辑用户信息
      modifyForm: {
        roleName: '',
        roleDesc: '',
      },
      modifyVisible: false,
      updateId: 0,
      // 角色id
    }
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data } = await this.$http.get('roles')
      this.rolesList = data.data
    },
    // 删除tag标签渲染的权限
    async removeRightByTagId(role, rightsId) {
      let isConfirm = await this.$confirm('确定删除该权限吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      if (!isConfirm) return this.$message.error('取消了删除权限操作')
      // 用户点击了确定
      const { data } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
      if (data.meta.status !== 200) return this.$message.error('删除了该权限')
      // 重新获取数据会导致页面重新渲染
      // this.getRolesList()

      // 上面这种方式会重新请求服务器加载所有的数据 更新rolesList 而rolesList的更新会引起依赖该数据的视图更新 而依赖他的视图是整个表格 所以整个表格会刷新 展开的列也会收起 需要重新打开才能看到最新的数据

      // 我们希望只有role对应的权限部分发生重新渲染
      // 所以我们只对role.children进行重新赋值
      // 赋值的是服务器返回的最新的role对应的权限
      role.children = data.data
    },
    // 点击分配权限的弹窗
    async rightsShow(role) {
      // 保存一份roleId
      this.roleId = role.id
      this.rightVisible = true
      // 获取所有子节点
      const { data } = await this.$http.get('rights/tree')
      console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = data.data
      // 递归将所有id放入checkedKeys数组中
      this.getKeys(role)
    },
    // 递归获取到所有选中的id
    getKeys(role) {
      if (!role.children) {
        return this.checkedKeys.push(role.id)
      }
      // 有子级
      role.children.forEach((item) => {
        this.getKeys(item)
      })
    },
    // 权限弹窗关闭时
    rightsNone() {
      // 清空权限树形菜单默认选中的选项
      this.checkedKeys = []
      // 关闭弹窗
      this.rightVisible = false
    },
    // 点击确定权限
    async updateRights() {
      // 合并选中和半选中的id
      let arrs = [...this.$refs.rightsTree.getCheckedKeys(), ...this.$refs.rightsTree.getHalfCheckedKeys()]
      // 以,分割
      arrs = arrs.join(',')
      console.log(arrs)
      // 发起请求
      const { data } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: arrs,
      })
      this.getRolesList()
      console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.$message.success('获取权限列表成功')
      // 关闭弹窗
      this.rightVisible = false
    },
    addRoles() {
      this.addVisible = true
    },
    addNode() {
      // 清空权限树形菜单默认选中的选项
      this.checkedKeys = []
      // 关闭弹窗
      this.rightVisible = false
    },
    async defineaddRoles() {
      const { data } = await this.$http.post('roles', this.addRoleForm)
      console.log(data)
      if (data.meta.status !== 201) return this.$message.error('创建失败')
      this.$message.success('创建成功')
      this.getRolesList()
      this.addVisible = false
    },

    // 修改内容
    async modify(role) {
      this.updateId = role.id
      this.modifyVisible = true
      console.log(this.modifyCon)
      const { data } = await this.$http.get(`roles/${role.id}`)
      if (data.meta.status !== 200) this.$message.error('获取失败')
      this.$message.success('获取信息成功')
      this.modifyForm.roleName = data.data.roleName
      this.modifyForm.roleDesc = data.data.roleDesc
    },
    // 点击确定发送请求
    async roleDefine() {
      this.modifyVisible = false
      const { data } = await this.$http.put(`roles/${this.updateId}`, this.modifyForm)
      if (data.meta.status !== 200) this.$message.error('编辑用户内容失败')
      this.$message.success('编辑用户内容成功')
      this.getRolesList()
    },
    // 删除角色信息
    removeRole(role) {
      this.$confirm(`是否确认删除用户${role.roleName}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 发起请求
          const { data } = await this.$http.delete(`roles/${role.id}`)
          if (data.meta.status !== 200) return this.$message.error('删除失败 请稍后重试！')
          // 删除成功
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch((data) => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  created() {
    this.getRolesList()
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 10px 0;
  margin-left: 15px;
}
.bt {
  border-top: 1px solid #f5f5f5;
}
.bb {
  border-bottom: 1px solid #f5f5f5;
}
.aic {
  display: flex;
  align-items: center;
}
</style>
